﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Documents;

namespace USpell.Controls
{
    public partial class SlideCanvas : UserControl
    {
        int curItem = 0;
        int _currentItem
        {
            get { return curItem; }
            set
            {
                if (curItem != value)
                {
                    BeginCircleStory();
                }
                curItem = value;
            }
        }
        public List<BitmapImage> _imgList;
        Canvas cav_Main;
        Canvas cav_View;
        Grid grid_Circle;
        Ellipse circle;
        TextBlock lab_PIndex;
        GestureListener gestListener;
        StackPanel sp_CircleTip;
        Storyboard sbMoveView;
        DoubleAnimation doubleAnimation;
        Storyboard sbCircleTip;
        DoubleAnimation circleAnimation;
        readonly SolidColorBrush brush_CirTipSelected = new SolidColorBrush(Color.FromArgb(255, 100, 230, 10));
        readonly SolidColorBrush brush_CirTipDefault = new SolidColorBrush(Color.FromArgb(255, 190, 200, 230));
        readonly SolidColorBrush brush_CirTipStroke = new SolidColorBrush(Color.FromArgb(255, 100, 100, 100));

        public event EventHandler StoryFinishEvent;
        public event EventHandler StorySelectedEvent;

        public SlideCanvas()
        {
            InitializeComponent();


            LoadImgList();

            CreateCanvas();
       
            CreateTopTip();
            CreateEllipse();

            gestListener = GestureService.GetGestureListener(this);
            gestListener.DragDelta += gestListener_DragDelta;
            gestListener.DragCompleted += gestListener_DragCompleted;
        }

        #region 图片Canvas

        /// <summary>
        /// 加载要滑动的图像资源
        /// </summary>
        private void LoadImgList()
        {
            _imgList = new List<BitmapImage>()
            { 
                new BitmapImage(new Uri(@"\Resources\Welcome\1.jpg",UriKind.Relative)),
                new BitmapImage(new Uri(@"\Resources\Welcome\2.jpg",UriKind.Relative)),
                new BitmapImage(new Uri(@"\Resources\Welcome\3.jpg",UriKind.Relative)),
                new BitmapImage(new Uri(@"\Resources\Welcome\2.jpg",UriKind.Relative)),
                new BitmapImage(new Uri(@"\Resources\Welcome\3.jpg",UriKind.Relative)),
                new BitmapImage(new Uri(@"\Resources\Welcome\4.jpg",UriKind.Relative)),
                new BitmapImage(new Uri(@"\Resources\Welcome\5.jpg",UriKind.Relative)),
            };
        }

        /// <summary>
        /// 有图像资源创建滑板
        /// </summary>
        private void CreateCanvas()
        {
            cav_Main = new Canvas() { Width = _imgList.Count * 480, Height = 800 };
            cav_View = new Canvas();
            Image im = new Image();

            double le = 0;
            _imgList.ForEach(item =>
            {
                Image img = new Image() { Source = item, Width = 480, Stretch = Stretch.Fill };
                img.CacheMode = new BitmapCache();  //必须指定缓存，不然超过4张图片，就会闪屏，和动画失真等异常问题
                img.SetValue(Canvas.LeftProperty, le);
                cav_View.Children.Add(img);
                le += 480;
            });

            cav_Main.Children.Add(cav_View);
            LayoutRoot.Children.Add(cav_Main);

            CreateCanvasStory();
        }

        /// <summary>
        /// 创建图片滑动动画效果
        /// </summary>
        private void CreateCanvasStory()
        {
            sbMoveView = new Storyboard();
            doubleAnimation = new DoubleAnimation();
            doubleAnimation.Duration = new Duration(TimeSpan.FromSeconds(1));
            Storyboard.SetTarget(doubleAnimation, cav_View);
            Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath(Canvas.LeftProperty));
            doubleAnimation.EasingFunction = new CubicEase() { EasingMode = EasingMode.EaseOut };
            sbMoveView.Completed += sbMoveView_Completed;
            sbMoveView.Children.Add(doubleAnimation);
        }

        void sbMoveView_Completed(object sender, EventArgs e)
        {
            if (StorySelectedEvent != null)
                StorySelectedEvent(_currentItem, null);
        }

        /// <summary>
        /// 开始图片滑动
        /// </summary>
        /// <param name="dTo"></param>
        private void BeginCanvasStory(double dTo)
        {
            doubleAnimation.To = dTo;
            sbMoveView.Begin();
        
        }

        #endregion

        #region 圆心导航

        /// <summary>
        /// 创建圆心页面导航
        /// </summary>
        private void CreateTopTip()
        {
            grid_Circle = new Grid();
            grid_Circle.VerticalAlignment = VerticalAlignment.Top;
            grid_Circle.HorizontalAlignment = HorizontalAlignment.Right;
            grid_Circle.Width = grid_Circle.Height = 50;
            grid_Circle.Margin = new Thickness(0, 16, -30, 0);
            grid_Circle.Projection = new PlaneProjection();
            grid_Circle.RenderTransform = new CompositeTransform() { Rotation = 90 };

            circle = new Ellipse();
            circle.Fill = brush_CirTipStroke;
            circle.Width = circle.Height = 46;
            circle.VerticalAlignment = VerticalAlignment.Center;
            circle.HorizontalAlignment = HorizontalAlignment.Center;

            lab_PIndex = new TextBlock();
            lab_PIndex.Text = "1";
            lab_PIndex.Foreground = new SolidColorBrush(Colors.Red);
            lab_PIndex.FontSize = 26;
            lab_PIndex.VerticalAlignment = VerticalAlignment.Center;
            lab_PIndex.HorizontalAlignment = HorizontalAlignment.Center;
            lab_PIndex.RenderTransformOrigin = new Point(0.5, 0.5);
            lab_PIndex.RenderTransform = new CompositeTransform() { Rotation = -90 };
            lab_PIndex.Projection = new PlaneProjection() { RotationX = 0 };
   
            grid_Circle.Children.Add(circle);
            grid_Circle.Children.Add(lab_PIndex);

            LayoutRoot.Children.Add(grid_Circle);

            CreateCircleStory();
        }

        private void CreateCircleStory()
        {
            sbCircleTip = new Storyboard();
            circleAnimation = new DoubleAnimation();
            circleAnimation.Duration = new Duration(TimeSpan.FromSeconds(0.6));
            Storyboard.SetTarget(circleAnimation, grid_Circle.Projection);
            Storyboard.SetTargetProperty(circleAnimation, new PropertyPath(PlaneProjection.RotationXProperty));

            circleAnimation.EasingFunction = new CubicEase() { EasingMode = EasingMode.EaseOut };
            sbCircleTip.Children.Add(circleAnimation);
        }

        bool IsrotationX = true;
        private void BeginCircleStory()
        {
            circleAnimation.To = IsrotationX ? 180 : 0;
            sbCircleTip.Begin();
            lab_PIndex.Projection = new PlaneProjection() { RotationY = IsrotationX ? 180 : 0 };

            IsrotationX = !IsrotationX;

        }

        #endregion

        #region 下方多元导航

        private void CreateEllipse()
        {
            sp_CircleTip = new StackPanel();
            sp_CircleTip.VerticalAlignment = VerticalAlignment.Bottom;
            sp_CircleTip.Margin = new Thickness(0, 0, 0, 25);
            sp_CircleTip.Orientation = Orientation.Horizontal;
            sp_CircleTip.HorizontalAlignment = HorizontalAlignment.Center;

            bool first = true;
            _imgList.ForEach(item =>
            {
                Ellipse tmp = new Ellipse();
                tmp.Fill = first ? brush_CirTipSelected : brush_CirTipDefault; //第一个默认选中
                tmp.Width = tmp.Height = 25;
                tmp.Margin = new Thickness(0, 0, 8, 0);
                sp_CircleTip.Children.Add(tmp);
                first = false;
            });

            LayoutRoot.Children.Add(sp_CircleTip);
        }

        #endregion

        // 手势滑动结束
        void gestListener_DragCompleted(object sender, DragCompletedGestureEventArgs e)
        {
            gestListener.DragDelta -= gestListener_DragDelta;

            if (e.Direction == System.Windows.Controls.Orientation.Horizontal)
            {
                bool IsToRight = e.HorizontalChange > 0;
                double dTo = 0;

                if (IsToRight && _currentItem <= 0)
                {
                    dTo = 0;
                    _currentItem = 0;
                }
                else if (!IsToRight && _currentItem >= cav_View.Children.Count - 1)
                {
                    _currentItem = cav_View.Children.Count - 1;
                    dTo = _currentItem * -480;

                    if (StoryFinishEvent != null) StoryFinishEvent(null, null);

                }
                else
                {
                    dTo = IsToRight ? (--_currentItem) * -480 : (++_currentItem) * -480;
                }

                BeginCanvasStory(dTo);
            

                lab_PIndex.Text = (_currentItem + 1).ToString();

                int cirIndex = 0;
                sp_CircleTip.Children.ToList().ForEach(item =>
                {
                    var tmp = item as Ellipse;
                    if (tmp != null)
                    {
                        tmp.Fill = cirIndex == _currentItem ? brush_CirTipSelected : brush_CirTipDefault;
                    }
                    cirIndex++;
                });

            }

            gestListener.DragDelta += gestListener_DragDelta;

        }

        // 手势滑动中
        void gestListener_DragDelta(object sender, DragDeltaGestureEventArgs e)
        {
            if (e.Direction == Orientation.Horizontal)
            {
                var oldLeft = Canvas.GetLeft(cav_View);
                double _left = oldLeft + e.HorizontalChange;
                if (_left > 0) _left = 0;
                if (_left < (cav_View.Children.Count - 1) * -480) _left = (cav_View.Children.Count - 1) * -480;
                Canvas.SetLeft(cav_View, _left);
            }
        }
    }
}